import router from './router'
import store from './store'
import {
  Message
} from 'element-ui'
import NProgress from 'nprogress' // 进度条
import 'nprogress/nprogress.css' // progress bar style
import {
  getToken
} from '@/utils/auth' //从cookie中获取token
import getPageTitle from '@/utils/get-page-title'
import {
  constantRoutes
} from './router/index'
NProgress.configure({
  showSpinner: false
}) // NProgress Configuration

const whiteList = ['/login', '/treatys', '/collectInfo', '/wxAccounts', '/wxAccounts/snDetails', '/wxAccounts/scan'] // 没有重定向白名单

router.beforeEach(async (to, from, next) => {

  // 开始进度条
  NProgress.start()
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  // 确定用户是否已经登录
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 如果已登录，则重定向到主页
      next({
        path: '/'
      })
      NProgress.done()
    } else {
      try {
        let accessRoutes = await store.dispatch('menus/getMenus')
        // console.log('...........最终渲染的菜单', accessRoutes)
        router.options.routes = constantRoutes.concat(accessRoutes)
        // router.addRoutes(constantRoutes.concat(accessRoutes))
        next()
      } catch (error) {
        // console.log('前往的路由1', to.path)
        // r删除令牌，转到登录页面重新登录
        await store.dispatch('user/resetToken')
        // Message.error(error || 'Has Error')
        next(`/login?redirect=${to.path}`)
        NProgress.done()
      }
    }
  } else {
    /* has no token*/
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免费登录白名单中，直接登录
      next()
    } else {
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach((to) => {
  // 完成进度条
  NProgress.done()
})
